package com.leha.mp.core.handler;

import com.leha.mp.core.builder.TextBuilder;
import com.leha.mp.core.dao.MpDoctorCodeMapper;
import com.leha.mp.core.dao.MpUserMapper;
import com.leha.mp.core.dao.QaDoctorMapper;
import com.leha.mp.core.entity.mybatis.MpDoctorCode;
import com.leha.mp.core.entity.mybatis.MpDoctorCodeExample;
import com.leha.mp.core.entity.mybatis.MpUser;
import com.leha.mp.core.entity.vo.DoctorBaseInfoVo;
import com.leha.mp.core.services.AppDoctorServices;
import com.leha.mp.core.services.MpUserServices;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 
 * @author Binary Wang
 *
 */
@Component
public class ScanHandler extends AbstractHandler {
    @Autowired
    MpDoctorCodeMapper mpDoctorCodeMapper;
    @Autowired
    MpUserMapper userMapper;
    @Autowired
    MpUserServices mpUserServices;
    @Autowired
    AppDoctorServices appDoctorServices;

    private MpUser UserInfoAdapter(WxMpUser u) {
        MpUser mu = new MpUser();
        mu.setOpenid(u.getOpenId());
        mu.setUnionid(u.getUnionId());
        mu.setNickname(u.getNickname());
        mu.setAvatarUrl(u.getHeadImgUrl());
        mu.setChannel(1);
        return mu;
    }
    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        this.logger.info("用户扫描二维码 OPENID: " + wxMessage.getFromUser());

        // 获取微信用户基本信息,保存到数据库中
        WxMpUser userWxInfo = wxMpService.getUserService().userInfo(wxMessage.getFromUser());
        mpUserServices.saveUser(UserInfoAdapter(userWxInfo));

        DoctorBaseInfoVo doctorInfo = null;
        try {
            doctorInfo = handleSpecial(wxMessage);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }
        if (doctorInfo != null) {
            if(userWxInfo.getUnionId()!=null) {
                mpUserServices.initRelation(userWxInfo.getUnionId(), doctorInfo.getId());
            }
            wxMpService.getTemplateMsgService().sendTemplateMsg(TemplateMsgHelper.ScanTemplateMsgBuilder(doctorInfo, wxMessage.getFromUser()));
            return null;
            //return new ImageAndContentBuilder().build("普乐云康", doctorInfo.getPhoto(), doctorInfo.getName()+"医生工作站", wxMessage);
        }
        try {
            return new TextBuilder().build("感谢关注", wxMessage);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }
        return new TextBuilder().build("感谢关注", wxMessage);
    }
    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    protected DoctorBaseInfoVo handleSpecial(WxMpXmlMessage wxMessage) throws Exception {
        if(wxMessage.getTicket()!=null) {
            MpDoctorCodeExample ex = new MpDoctorCodeExample();
            ex.createCriteria().andTicketEqualTo(wxMessage.getTicket());
            List<MpDoctorCode> res = mpDoctorCodeMapper.selectByExample(ex);
            if(res.size()>0) {
                return appDoctorServices.getDoctorBaseInfo(res.get(0).getDoctorId());
            }
        }
        return null;
    }
}
